
require('./utils/strophe.js')
var WebIM = require('./utils/WebIM.js').default
var msgArr = []
var chatMsg = []
var chcity;
var cityId;
var lat1;
var lng1;
var usercity;
var personArr = []
var https = "https://www.moreclub.cn/";
var QQMapWX = require('./utils/qqmap-wx-jssdk.min.js')
var qqmapsdk = new QQMapWX({
  key: 'WYUBZ-QQ6C5-KL5IO-QCQQX-VA4XV-YVFPK'
});

var getList=function(message){
  //模版消息
  
  var openid = wx.getStorageSync('openid')
  var token = wx.getStorageSync('token')
  var fId = wx.getStorageSync('fId')
  
  // let formIds = that.globalData.gloabalFomIds;
  // if (!formIds){
  //   formIds = [];
  //   let data = {
  //     formId: fId,
  //     expire: parseInt(new Date().getTime() / 1000) + 604800 //计算7天后的过期时间时间戳
  //   }
  //   formIds.push(data);
  //   that.globalData.gloabalFomIds = formIds; //保存推送码并赋值给全局变量
  // } 

  // var time = new Date()
  // var year = time.getFullYear()
  // var month = time.getMonth() + 1
  // var day = time.getDate()
  // var l = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + token
  // wx.request({
  //   url: l,
  //   data: {
  //     "touser": openid,
  //     "template_id": 'W995i30kfciShJcgZGiaUHGQgzWS1iCqLzqfQaZNYiQ',//这个是1、申请的模板消息id，
  //     "page": 'index',
  //     "form_id": fId,
  //     "data": {
  //       "keyword1": {
  //         "value": message.ext.nickName + '给你发了一条消息',
  //         "color": "#4a4a4a"
  //       },
  //       "keyword2": {
  //         "value": message.ext.nickName,
  //         "color": "#9b9b9b"
  //       },
  //       "keyword3": {
  //         "value": year+ '/' + month + '/' + day,
  //         "color": "#9b9b9b"
  //       }

  //     },
  //     "color": '#ccc',
  //     // "emphasis_keyword": 'keyword1.DATA'
  //   },
  //   method: 'POST',
  //   success: function (res) {
  //     console.log("push msg");
  //     console.log(res);
  //   },
  //   fail: function (err) {
  //     // fail
  //     console.log("push err")
  //     console.log(err);
  //   }
  // }); 
}

//app.js   
App({
  getRoomPage: function () {
    return this.getPage("pages/chat/chat")
  },
  getPage: function (pageName) {
    var pages = getCurrentPages()
    return pages.find(function (page) {
      return page.__route__ == pageName
    })
  },

  
  
  onLaunch: function () {
    //调用API从本地缓存中获取数据
   
    var that = this

    
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // if (WebIM.config.isDebug) {
    //     var options = {
    //         apiUrl: WebIM.config.apiURL,
    //         user: 'lwz3',
    //         pwd: '1',
    //         grant_type: 'password',
    //         appKey: WebIM.config.appkey
    //     }
    //     WebIM.conn.open(options)
    // }

        //1、调用微信登录接口，获取code
    wx.login({
      success: function (res) {
        var code = res.code;//登录凭证
        // console.log(code);
        // that.setData({ code: code })
        if (code) {
          //2、调用获取用户信息接口
          wx.getUserInfo({
            success: function (res) {

              var time = Date.parse(new Date()) / 1000;

              //3.请求自己的服务器，解密用户信息 获取unionId等加密信息
              wx.request({
                url: 'https://www.moreclub.cn/v1/user/open/minilogin',//自己的服务接口地址
                //url:'http://10.150.7.245:8006/v1/user/open/minilogin',
                //url:'http://59.110.53.149:8088/v1/user/open/minilogin',
                //url: 'http://10.150.7.248:8001/v1/user/open/minilogin' ,
                method: 'POST',
                header: {
                  'content-type': 'application/json'
                },
                data: {
                  encryptedData: res.encryptedData,
                  iv: res.iv, code: code,
                  appId: 'wxcaa829aa1df78b58',
                  appSecret: '38242ce22873c90fbaeec232f6aa9756',
                  appkey: "c57150e212a5498d9436ec7f51662361",
                  loginType: 4,
                  machine: "miniapp",
                  opSystem: "miniapp",
                  version: "v1.1.1",
                  appVersion: "v1.1.1",
                  loginTime: time,
                  channel: 2
                },
                success: function (res) {

                  console.log(res.data);
                 var uid = res.data.data.uid;
                 var myName = res.data.data.nickname;
                 var access_token = res.data.data.access_token;
                
                  try {
                    wx.setStorageSync('uid', res.data.data.uid);
                    wx.setStorageSync('openid', res.data.data.openid);
                    wx.setStorageSync('applogin', res.data.data.applogin);
                    wx.setStorageSync('myUsername', res.data.data.nickname)
                    wx.setStorageSync('inToken', res.data.data.access_token)
                    wx.setStorageSync('thumb', res.data.data.thumb)
                    wx.setStorageSync('sex', res.data.data.sex)
                  } catch (e) {
                  }

                  //var fromId = wx.getStorageSync('fromId'); 
                  //var mid = wx.getStorageSync('mid');
                  //var mid = 200 
                  // if (fromId == 0) {

                  //   wx.request({
                  //     url: https + 'v1/signin/miniapp?uid=' + uid + '&access_token=' + access_token,
                  //     method: 'POST',
                  //     header: {
                  //       'content-type': 'application/json',
                  //     },
                  //     data: {
                  //       // 'userLat': '30.632938',
                  //       // 'userLng': '104.054685',
                  //       'mid': mid,
                  //       'merchantName': '',
                  //       'userLat': 0,
                  //       'userLng': 0,
                  //       'uid': uid,
                  //       'userName': myName,
                  //       'access_token': access_token

                  //     },
                  //     success: function (res) {
                  //       console.log(res)
                  //       var signData = res.data.data;
                  //       if (res.data.success){
                  //         wx.setStorage({
                  //           key: "signData2",
                  //           data: signData
                  //         })
                  //       }
                       

                      
                  //       try {
                  //         wx.removeStorageSync('fromId')
                  //         wx.removeStorageSync('mid')
                  //       } catch (e) {
                  //       }
                  //     },
                  //     fail: function (){
                  //       try {
                  //         wx.removeStorageSync('fromId')
                  //         wx.removeStorageSync('mid')
                  //       } catch (e) {
                  //       }
                  //     }
                  //   })

                  // }
        
                },
                fail: function () {
                  console.log('系统错误')
                }
              })
            },
            fail: function () {
              console.log('获取用户信息失败')
            }
          })

        } else {
          console.log('获取用户登录态失败！' + r.errMsg)
        }
      },
      fail: function () {
        console.log('登陆失败')
      },

      
    })


   

    var MsgArr = []
    var uid = wx.getStorageSync('uid');
    var mid = wx.getStorageSync('mid');
    var access_token = wx.getStorageSync('inToken');

    // //环信登录
    // var options = {
    //   apiUrl: WebIM.config.apiURL,
    //   user: '' + uid,
    //   pwd: 'm' + uid,
    //   grant_type: 'password',
    //   appKey: WebIM.config.appkey //应用key
    // }
    // console.log(options)
    // WebIM.conn.open(options)

    WebIM.conn.listen({
      onOpened: function (message) {
        //console.log("kkkkkkk1")

        WebIM.conn.setPresence()
        // WebIM.conn.getRoster(rosters)
      },
      onPresence: function (message) {
        //console.log('onPresence',message)
        var pages = getCurrentPages()
        if (message.type == "unsubscribe") {
          pages[0].moveFriend(message)
        }
        if (message.type === "subscribe") {
          //console.log('MMMMMMMMMMMMMM',message.status)
          if (message.status === '[resp:true]') {
            return
          } else {
            pages[0].handleFriendMsg(message)
          }
        }
      },
      onRoster: function (message) {
        //console.log('onRoster',message)
        var pages = getCurrentPages()
        if (pages[0]) {
          pages[0].onShow()
        }
      },
     
      onAudioMessage: function (message) {
        console.log('onAudioMessage', message)
        wx.setStorage({
          key: "chatMsg1",
          data: message
        })
        message.type = 'audio'
       
        var page = that.getRoomPage()

        console.log(page)
        if (message) {
          wx.setTopBarText({
            text: '你收到一条新消息，请查看'
          })
       
          if (page) {
            page.receiveMsg(message, 'audio')
           
          } else {
            var chatMsg = that.globalData.chatMsg || []
            var value = message.url
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.ext.nickName,
              yourname: message.from,
              headerUrl: message.ext.headerUrl,
              msg: {
                type: 'audio',
                data: value
              },
              style: '',
              time: time,
              mid: 'audio' + message.id
            }
            msgArr.push(msgData)
            
            chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
            chatMsg.push(msgData)
            
            var obj = {}
            obj.id = message.from
            obj.name = message.ext.nickName
            obj.pic = message.ext.headerUrl


            var isext = false;
            for (var i = 0; i < personArr.length; i++) {
              if (personArr[i].id == obj.id) {
                var MsgArr = personArr[i].MsgArr || []
                //var o = msgData
                var o = {}
                o.time = time
                o.data = []
                var t = {}
                t.data = value
                t.type = 'audio'
                o.data.push(t)
                MsgArr.unshift(o)
                console.log(MsgArr)
                obj.MsgArr = MsgArr
                obj.isShow = true
                isext = true;
                personArr[i] = obj
                break;
              }

            }
            if (!isext) {
              var MsgArr = []
              var o = {}
              o.time = time
              o.data = []
              var t = {}
              t.data = value
              t.type = 'audio'
              o.data.push(t)
              MsgArr.push(o)
              console.log(MsgArr)
              obj.MsgArr = MsgArr
              obj.isShow = true
              isext = true;
              personArr.unshift(obj)

            }
            console.log('personArr', personArr)



            try {

              wx.setStorageSync('personArr', personArr)
            } catch (e) {
            }
            wx.setStorage({
              key: msgData.yourname + message.to,
              data: chatMsg,
              success: function () {
                //console.log('success')
              }
            })
          }
        }
      },
      onTextMessage: function (message) {
        getList(message)

        personArr = wx.getStorageSync('personArr') || [];
        wx.setStorage({
          key: "chatMsg1",
          data: message
        })
        message.type = 'txt'
       
      
        //var chatMsg1 = message
       
        var page = that.getRoomPage()
       
        console.log(page)
        if (message) {
          wx.setTopBarText({
            text: '你收到了新消息，请查看'
          })

          
          if (page) {
            page.receiveMsg(message, 'txt')
           
          } else {
            var chatMsg = that.globalData.chatMsg || []
            var value = WebIM.parseEmoji(message.data.replace(/\n/mg, ''))
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.ext.nickName,
              yourname: message.from,
              headerUrl: message.ext.headerUrl,
              msg: {
                type: 'txt',
                data: value
              },
              style: '',
              time: time,
              mid: 'txt' + message.id
            }
            msgArr.push(msgData)
            console.log(msgArr)
        
            chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
            
            console.log(chatMsg)
            // msgArr.push(chatMsg)
            
            var obj = {}
              obj.id = message.from
              obj.name = message.ext.nickName
              obj.pic = message.ext.headerUrl
        
           
            var isext = false;
            for(var i=0;i<personArr.length;i++){
              if(personArr[i].id == obj.id){
                var MsgArr = personArr[i].MsgArr || []
                //var o = msgData
                var o = {}
                o.time = time
                o.data = value
                MsgArr.unshift(o)
                console.log(MsgArr)
                obj.MsgArr = MsgArr
                obj.isShow = true
                  isext = true;
                  personArr[i] = obj 
                //  var str = personArr.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                // personArr = str.splice(0, 0, personArr[i]);
                //  console.log(personArr)
                  break;
              }
             
            }
            if(!isext){
              var MsgArr = []
              var o = {}
              o.time = time
              o.data = value
              MsgArr.push(o)
              console.log(MsgArr)
              obj.MsgArr = MsgArr
              obj.isShow = true
              isext = true;
                personArr.unshift(obj)
               

            }
            console.log('personArr', personArr)
            
             

            try {
             
              wx.setStorageSync('personArr', personArr)
            } catch (e) {
            }
        
            wx.setStorage({
              key: msgData.yourname + message.to,
              data: chatMsg,
              success: function () {
                //console.log('success')
              },
             
            })
          }
        }
      },
      onEmojiMessage: function (message) {
        console.log('onEmojiMessage',message)
        wx.setStorage({
          key: "chatMsg1",
          data: message
        })
        message.type = 'emoji'
       
        var page = that.getRoomPage()
        //console.log(pages)
        if (message) {
          wx.setTopBarText({
            text: '你收到一条新消息，请查看'
          })

        
          if (page) {
            page.receiveMsg(message, 'emoji')
          } else {
            var chatMsg = that.globalData.chatMsg || []
            var value = message.data
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.ext.nickName,
              yourname: message.from,
              headerUrl: message.ext.headerUrl,
              msg: {
                type: 'emoji',
                data: message.data
              },
              style: '',
              time: time,
              mid: 'emoji' + message.id
            }
            msgData.style = ''
            msgArr.push(msgData)
           
            chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
            chatMsg.push(msgData)
            //console.log(chatMsg)

            var obj = {}
            obj.id = message.from
            obj.name = message.ext.nickName
            obj.pic = message.ext.headerUrl
            var MsgArr = obj.MsgArr || []

            var obj = {}
            obj.id = message.from
            obj.name = message.ext.nickName
            obj.pic = message.ext.headerUrl
            obj.isShow = true


            var isext = false;
            for (var i = 0; i < personArr.length; i++) {
              if (personArr[i].id == obj.id) {
                var MsgArr = personArr[i].MsgArr || []
                //var o = msgData
                var o = {}
                o.time = time
                o.data = value
                MsgArr.unshift(o)
                console.log(MsgArr)
                obj.MsgArr = MsgArr
                obj.isShow = true
                isext = true;
                personArr[i] = obj
                break;
              }

            }
            if (!isext) {
              var MsgArr = []
              var o = {}
              o.time = time
              o.data = value
              MsgArr.push(o)
              console.log(MsgArr)
              obj.MsgArr = MsgArr
              isext = true;
              personArr.unshift(obj)

            }

            try {
              wx.setStorageSync('personArr', personArr)
            } catch (e) {
            }

            console.log('personArr', personArr)


            wx.setStorage({
              key: msgData.yourname + message.to,
              data: chatMsg,
              success: function () {
                //console.log('success')
              }
            })
          }
        }
      },
      onPictureMessage: function (message) {
        wx.setStorage({
          key: "chatMsg1",
          data: message
        })
        //console.log('Picture',message);
        message.type = 'img'
       
        var page = that.getRoomPage()
        if (message) {
          wx.setTopBarText({
            text: '你收到一条新消息，请查看'
          })

        
          if (page) {
            //console.log("wdawdawdawdqwd")
            page.receiveImage(message, 'img')
          } else {
            var chatMsg = that.globalData.chatMsg || []
            var value = message.url
            var time = WebIM.time()
            var msgData = {
              info: {
                from: message.from,
                to: message.to
              },
              username: message.ext.nickName,
              yourname: message.from,
              headerUrl: message.ext.headerUrl,
              msg: {
                type: 'img',
                data: message.url
              },
              style: '',
              time: time,
              mid: 'img' + message.id
            }

            msgArr.push(msgData)
           
            msgData.style = ''
            chatMsg = wx.getStorageSync(msgData.yourname + message.to) || []
            chatMsg.push(msgData)

            var obj = {}
            obj.id = message.from
            obj.name = message.ext.nickName
            obj.pic = message.ext.headerUrl


            var isext = false;
            for (var i = 0; i < personArr.length; i++) {
              if (personArr[i].id == obj.id) {
                var MsgArr = personArr[i].MsgArr || []
                //var o = msgData
                var o = {}
                o.time = time
                // o.data = []
                // var t ={}
                // t.data = value
                // t.type = 'img'
                // o.data.push(t)
                o.data = value
                o.type = 'img'
                MsgArr.unshift(o)
                console.log(MsgArr)
                obj.MsgArr = MsgArr
                obj.isShow = true
                isext = true;
                personArr[i] = obj
                break;
              }

            }
            if (!isext) {
              var MsgArr = []
              var o = {}
              o.time = time
              // o.data = []
              // var t = {}
              // t.data = value
              // t.type = 'img'
              // o.data.push(t)
              o.data = value
              o.type = 'img'
              MsgArr.push(o)
              console.log(MsgArr)
              obj.MsgArr = MsgArr
              obj.isShow = true
              isext = true;
              personArr.unshift(obj)

            }
            console.log('personArr', personArr)


            try {

              wx.setStorageSync('personArr', personArr)
            } catch (e) {
            }

            wx.setStorage({
              key: msgData.yourname + message.to,
              data: chatMsg,
              success: function () {
                //console.log('success')
              }
            })
          }
        }
      },
     
    })
    var APPID = "wxcaa829aa1df78b58";
    var APPSECRET = "38242ce22873c90fbaeec232f6aa9756";
    wx.request({
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + APPSECRET,
      success: function (res) {
        console.log(res)
        try {
          wx.setStorageSync('token', res.data.access_token);
        } catch (e) {
        }
      }
    })

    
  },
  onShow: function (options) {
    var uid = wx.getStorageSync('uid');
   personArr = wx.getStorageSync('personArr')||[]
 

    //环信登录
    var options = {
      apiUrl: WebIM.config.apiURL,
      user: '' + uid,
      pwd: 'm' + uid,
      grant_type: 'password',
      appKey: WebIM.config.appkey //应用key
    }
    console.log(options)
    WebIM.conn.open(options)
  },
  globalData: {
    userInfo: null,
    chatMsg: msgArr,
    gloabalFomIds:null
  }
})


